package com.stx.openeyes.view.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.stx.openeyes.MainActivity;
import com.stx.openeyes.R;
import com.stx.openeyes.SealConst;
import com.stx.openeyes.dto.Response;
import com.stx.openeyes.model.User;
import com.stx.openeyes.utils.AMUtils;
import com.stx.openeyes.utils.ContextUtil;
import com.stx.openeyes.utils.HttpAdress;
import com.stx.openeyes.utils.NToast;
import com.stx.openeyes.widget.ClearWriteEditText;
import com.stx.openeyes.widget.LoadDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private final static String TAG = "LoginActivity";

    private ImageView mImg_Background;
    private ClearWriteEditText mPhoneEdit, mPasswordEdit;
    private String phoneString;
    private String passwordString;
    private SharedPreferences sp;
    private SharedPreferences.Editor configEditor;
    protected Context mContext;
    private Gson mGson;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_activity_login);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

        sp = getSharedPreferences(SealConst.CONFIG, MODE_PRIVATE);
        configEditor = sp.edit();
        mContext = this;
        initView();
    }

    @SuppressLint("LongLogTag")
    private void initView() {
        mPhoneEdit = (ClearWriteEditText) findViewById(R.id.de_login_phone);
        mPasswordEdit = (ClearWriteEditText) findViewById(R.id.de_login_password);
        Button mConfirm = (Button) findViewById(R.id.de_login_sign);
        TextView mRegister = (TextView) findViewById(R.id.de_login_register);
        mConfirm.setOnClickListener(this);
        mRegister.setOnClickListener(this);
        mImg_Background = (ImageView) findViewById(R.id.de_img_backgroud);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Animation animation = AnimationUtils.loadAnimation(LoginActivity.this, R.anim.translate_anim);
                mImg_Background.startAnimation(animation);
            }
        }, 200);
        mPhoneEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 11) {
                    AMUtils.onInactive(mContext, mPhoneEdit);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        String oldPhone = sp.getString(SealConst.SEALTALK_LOGING_PHONE, null);
        String oldPassword = sp.getString(SealConst.SEALTALK_LOGING_PASSWORD, null);
        if (!TextUtils.isEmpty(oldPhone) && !TextUtils.isEmpty(oldPassword)) {
            mPhoneEdit.setText(oldPhone);
            mPasswordEdit.setText(oldPassword);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.de_login_sign:
                phoneString = mPhoneEdit.getText().toString().trim();
                passwordString = mPasswordEdit.getText().toString().trim();

                if (TextUtils.isEmpty(phoneString)) {
                    NToast.shortToast(mContext, R.string.phone_number_is_null);
                    mPhoneEdit.setShakeAnimation();
                    return;
                }

                if (!AMUtils.isMobile(phoneString)) {
                    NToast.shortToast(mContext, R.string.Illegal_phone_number);
                    mPhoneEdit.setShakeAnimation();
                    return;
                }

                if (TextUtils.isEmpty(passwordString)) {
                    NToast.shortToast(mContext, R.string.password_is_null);
                    mPasswordEdit.setShakeAnimation();
                    return;
                }
                if (passwordString.contains(" ")) {
                    NToast.shortToast(mContext, R.string.password_cannot_contain_spaces);
                    mPasswordEdit.setShakeAnimation();
                    return;
                }
                LoadDialog.show(mContext);

                requestLogin(phoneString, passwordString);
                break;
            case R.id.de_login_register:
                startActivityForResult(new Intent(this, RegisterActivity.class), 1);
                break;
        }
    }

    private void requestLogin(String mobile, String password) {
        OkHttpUtils.get()
            .url(HttpAdress.LOGIN)
            .addParams("mobile", mobile)
            .addParams("password", password)
            .addHeader("deviceId", ContextUtil.getDevicedId())
            .build()
            .execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    Log.i("===login error", e.getMessage());
                    NToast.shortToast(mContext, SealConst.NETWORK_ERROR);
                    LoadDialog.dismiss(mContext);
                }

                @Override
                public void onResponse(String response, int id) {
                    Log.i("===login response json", response);
                    mGson = new Gson();
                    Response<User> loginResp = mGson.fromJson(response, new TypeToken<Response<User>>() {}.getType());
                    if (!loginResp.isSuccess()) {
                        NToast.shortToast(mContext, loginResp.getMessage());
                        LoadDialog.dismiss(mContext);
                        return;
                    }
                    User useInfo = loginResp.getData();
                    LoadDialog.dismiss(mContext);
                    SharedPreferences settings = getSharedPreferences(SealConst.USER_INFO, 0);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString(SealConst.SEALTALK_LOGIN_ID, useInfo.getUuid());
                    editor.commit();
                    //startActivity(new Intent(LoginActivity.this, FunctionActivity.class));
                    configEditor.putString(SealConst.SEALTALK_LOGING_PHONE, mobile);
                    configEditor.putString(SealConst.SEALTALK_LOGING_PASSWORD, password);
                    configEditor.apply();
                    startActivity(new Intent(mContext, MainActivity.class));
                }
            });
    }
}
